package com.hmdp.controller;


import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@RestController
@RequestMapping("/follow")
public class FollowController {
    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Resource
    IUserService userService;

    @Resource
    IFollowService followService;
    @GetMapping("or/not/{id}")
    public Result isFollowed(@PathVariable("id") Long id){
        return followService.isFollowed(id);

    }
    @PutMapping("/{id}/{isFollow}")
    public Result follow(@PathVariable("id") Long id,@PathVariable("isFollow") Boolean isFollow){
       return followService.follow(id,isFollow);
    }
    @GetMapping("/common/{id}")
    public Result commonFollow(@PathVariable("id") Long id){
        //获取当前用户
        String key = "follower:"+ UserHolder.getUser().getId();
        String key1 = "follower:"+id;
        Set<String> ids = stringRedisTemplate.opsForSet().intersect(key, key1);
        List<Long> list = ids.stream().map(Long::valueOf).collect(Collectors.toList());
        if (list == null || list.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        List<UserDTO> userDTOS = userService.listByIds(list).stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class)).collect(Collectors.toList());
        return Result.ok(userDTOS);
    }

}
